package st.business.tepth.business.user.busnumber.workholder.dialog;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jakewharton.rxbinding2.widget.RxTextView;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import st.business.tepth.R;
import st.business.tepth.base.OnItemChooseListener;
import st.business.tepth.business.bean.PartBean;
import st.business.tepth.business.bean.SearchPartBean;
import st.business.tepth.config.Url;
import st.business.tepth.manager.UserManager;
import st.business.tepth.view.ClearEditText;
import st.shadow.library.core.net.data.ObjConverter;
import st.shadow.library.core.net.rx.RxRestClient;
import st.shadow.library.core.util.utilcode.util.ScreenUtils;
import st.shadow.library.ui.recycler.BaseDecoration;

/**
 * @author zhangyu
 * @date 2019/2/18
 * 零部件选择
 */
public class DialogPartChoose extends Dialog {
    private Disposable mDisposable;

    public DialogPartChoose(Context context,
                            final int repairId,
                            final OnItemChooseListener<PartBean> listener,
                            final boolean isPart) {
        super(context);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view = LayoutInflater.from(context).
                inflate(R.layout.dialog_part_choose, null);
        ((TextView) view.findViewById(R.id.tv_choose_action))
                .setText(isPart ? "选择零部件" : "选择耗材");
        ((TextView) view.findViewById(R.id.tv_common_part))
                .setText(isPart ? "推荐零部件" : "推荐耗材");
        ((EditText) view.findViewById(R.id.et_search))
                .setHint(isPart ? "请输入关键字搜索零部件" :
                        "请输入关键字搜索耗材");
        view.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        ClearEditText etSearch = view.findViewById(R.id.et_search);
        final RecyclerView recyclerViewSearch = view.findViewById(R.id.recycler_view_part_result);
        recyclerViewSearch.setLayoutManager(new LinearLayoutManager(context));
        final SearchPartAdapter searchPartAdapter = new SearchPartAdapter(R.layout.item_part_search, null);

        recyclerViewSearch.setAdapter(searchPartAdapter);
        recyclerViewSearch.addItemDecoration(BaseDecoration.
                create(Color.parseColor("#f0f0f0"), 1));
        recyclerViewSearch.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (listener != null) {
                    PartBean partBean = (PartBean) adapter.getItem(position);
                    if (partBean != null) {
                        int id = partBean.getId();
                        partBean.setParts_id(id);
                        partBean.setVal(1);
                        listener.onChoose(partBean);
                    }
                }
                dismiss();
            }
        });
        //推荐的
        RecyclerView recyclerViewCommon = view.findViewById(R.id.recycler_view_common_part);
        recyclerViewCommon.setLayoutManager(new LinearLayoutManager(context));
        recyclerViewCommon.setAdapter(new SearchPartAdapter(R.layout.item_part_search, null));
        recyclerViewCommon.addItemDecoration(BaseDecoration.
                create(Color.parseColor("#f0f0f0"), 1));
        recyclerViewCommon.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (listener != null) {
                    PartBean partBean = (PartBean) adapter.getItem(position);
                    if (partBean != null) {
                        int id = partBean.getId();
                        partBean.setParts_id(id);
                        partBean.setVal(1);
                        listener.onChoose(partBean);
                    }
                }
                dismiss();
            }
        });
        Observer observable = RxTextView.textChanges(etSearch)
                .subscribeOn(AndroidSchedulers.mainThread())
                .debounce(600, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
                .filter(new Predicate<CharSequence>() {
                    @Override
                    public boolean test(CharSequence charSequence) throws Exception {
                        if (charSequence.length() == 0) {
                            recyclerViewSearch.setVisibility(View.GONE);
                        } else {
                            searchPartAdapter.setEmptyView(R.layout.view_loading,
                                    (ViewGroup) recyclerViewSearch.getParent());
                            recyclerViewSearch.setVisibility(View.VISIBLE);
                        }
                        return charSequence.length() > 0;
                    }
                })
                .switchMap(new Function<CharSequence, Observable<String>>() {
                    @Override
                    public Observable<String> apply(CharSequence charSequence) throws Exception {
                        return RxRestClient.builder()
                                .url(isPart ? Url.GetPartListBySearch :
                                        Url.GetConsumableList)
                                .params("token", UserManager.getInstance().getToken())
                                .params("pageNumber", 1)
                                .params("pageSize", 50)
                                .params("repairId", repairId)
                                .params("materialName", charSequence.toString())
                                .build()
                                .onlyPost();
                    }
                })
                .subscribeWith(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(String response) {
                        searchPartAdapter.setEmptyView(R.layout.view_search_empty,
                                (ViewGroup) recyclerViewSearch.getParent());
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String object = jsonObject.getString("data");
                        String ResultMsg = jsonObject.getString("msg");
                        SearchPartBean searchPartBean =
                                new ObjConverter<SearchPartBean>().convert(object
                                        , new TypeReference<SearchPartBean>() {
                                        });
                        if (searchPartBean != null) {
                            searchPartAdapter.setNewData(searchPartBean.getList());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
        setContentView(view);
    }

    @Override
    public void dismiss() {
        if (mDisposable != null) {
            mDisposable.dispose();
        }
        super.dismiss();
    }

    private class SearchPartAdapter extends BaseQuickAdapter<PartBean, BaseViewHolder> {

        SearchPartAdapter(int layoutResId, @Nullable List<PartBean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, PartBean item) {

            helper.setText(R.id.tv_part_name, item.getMaterial_name());
            helper.setText(R.id.tv_part_type, "零部件:" + item.getMaterial_no());
            helper.setText(R.id.tv_brand, "品牌:" + item.getBrand());
            helper.setText(R.id.tv_version, "型号:" + item.getModel_no());
            helper.setText(R.id.tv_specification, "规格:" + item.getSpecifications());
            helper.setText(R.id.tv_batch, "批次:" + item.getBatch_no());
        }
    }

    public Dialog measureSize(){
        Window dialogWindow = getWindow();
        if (dialogWindow != null) {
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = ScreenUtils.getScreenWidth() * 1000 / 1280; // 宽度
            lp.height = ScreenUtils.getScreenHeight() * 720 / 1024; // 高度
            dialogWindow.setGravity(Gravity.CENTER);
            dialogWindow.setAttributes(lp);
        }
        return this;
    }
}
